const publicClass = require('../module/publicClass.js')
// 添加公示信息
class addopinion extends publicClass {
	constructor(req, res, neth) {
		super(req, res, neth)
		this.regtoken()
	}
	onload() {
		let data = this.req.body
		if (data.publicity_number) return this.update(data)
		if (!data.publicity_name) return this.sendform(0, '公示名称不能为空')
		let {
			generationNumber,
			toTimeString
		} = require('../util/util.js')
		data.publicity_number = generationNumber()
		data.publicity_time = toTimeString(Date.now())
		data.update_time = toTimeString(Date.now())
		let sql = 'insert into publicity_tab set ?'
		this.query(sql, data).then(res => {
			if (res.affectedRows < 1) return this.sendform(0, '添加失败')
			this.sendform(1, '添加成功')
		})
	}
	update(data) {
		var sql = 'update publicity_tab set ? where publicity_number=?'
		let {
			toTimeString
		} = require('../util/util.js')
		data.update_time = toTimeString(Date.now())
		this.query(sql, [data, data.publicity_number]).then(res => {
			if (res.affectedRows < 1) return this.sendform(0, '修改失败')
			this.sendform(1, '修改成功')
		})
	}
}
class getopinion extends publicClass {
	constructor(req, res, neth) {
		super(req, res, neth)
		this.regtoken()
	}
	async onload(data) {
		if (data.user_type != 1) return this.sendform(0, '没有权限', )
		try{
			var {
				page,
				pageNum,
				search
			} = this.req.query
			page = parseInt(page < 1 ? 1 : page)
			pageNum = parseInt(pageNum || 10)
			if(!search)search={}
			// 分页开始位置
			let startPosition = parseInt((page - 1) * pageNum)
			let countSql = `SELECT COUNT(_id) AS count FROM publicity_tab`;
			// 总页数
			let pageCont = await this.query(countSql, [])
			let total = pageCont[0].count
			pageCont = Math.ceil(pageCont[0].count / pageNum);
			var sql = `select publicity_number,publicity_name,publicity_type,
				publicity_data,publicity_time,remarks from publicity_tab ORDER BY update_time DESC `
			// 遍历需要进行搜索的字段
			let LIKESTR = ''
			let objKey = Object.keys(search)
			objKey.forEach((Key, index) => {
				let str = ` ${Key} LIKE "%${search[Key]}%" `
				if (index + 1 != objKey.length) str += 'and'
				LIKESTR += str
			})
			let sqlArr = [startPosition, pageNum]
			if (objKey.length) {
				sql += ' where'
				sql += LIKESTR
				sql += ' LIMIT ?,?'
			} else {
				sql += ' LIMIT ?,?'
			}
			this.query(sql, sqlArr).then(res => {
				let data = {
					page,
					pageNum,
					pageCont,
					total,
					items: res
				}
				this.sendform(1, 'success', data)
			}, err => this.neth(err))
		}catch(err){
			this.neth(err)
		}
	}
}
class delopinion extends publicClass {
	constructor(req, res, neth) {
		super(req, res, neth)
		this.regtoken()
	}
	onload(){
		if(!this.req.body.id) return this.sendform(0,'编号不能为空')
		var sql='delete from publicity_tab where publicity_number=?'
		this.query(sql,this.req.body.id).then(res=>{
			this.sendform(1,'删除成功')
		})
	}
}
module.exports = {
	addopinion,
	getopinion,
	delopinion
}
